package com.onlinelearn.courseservice.service;

import com.onlinelearn.courseservice.dto.HomeworkSubmissionDTO;
import com.onlinelearn.courseservice.model.Homework;
import com.onlinelearn.courseservice.repository.HomeworkRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class HomeworkService {
    @Autowired
    private HomeworkRepository homeworkRepository;

    @Autowired
    private NotificationTriggerService notificationService;

    public HomeworkSubmissionDTO submitHomework(HomeworkSubmissionDTO submissionDTO) {
        Homework homework = homeworkRepository.findById(submissionDTO.getHomeworkId())
                .orElseThrow(() -> new RuntimeException("作业未找到"));

        // 提交作业的逻辑
        return submissionDTO;
    }

    public void gradeHomework(Long homeworkId, Long studentId, Integer grade) {
        Homework homework = homeworkRepository.findById(homeworkId)
                .orElseThrow(() -> new RuntimeException("作业未找到"));

        // 批改作业的逻辑
    }

    public HomeworkSubmissionResult submitHomework(Long studentId, Long homeworkId, MultipartFile file) {
        Homework homework = homeworkRepository.findById(homeworkId)
            .orElseThrow(() -> new HomeworkNotFoundException(homeworkId));

        // 检查作业是否在截止日期内
        if (LocalDateTime.now().isAfter(homework.getDeadline())) {
            return HomeworkSubmissionResult.late(homework);
        }

        // 处理文件上传
        String fileUrl = uploadHomeworkFile(studentId, homeworkId, file);

        // 保存作业提交记录
        HomeworkSubmission submission = new HomeworkSubmission();
        submission.setStudentId(studentId);
        submission.setHomeworkId(homeworkId);
        submission.setFileUrl(fileUrl);
        submission.setSubmissionTime(LocalDateTime.now());
        submission.setStatus(HomeworkSubmissionStatus.SUBMITTED);

        homeworkRepository.save(submission);

        // 发送作业提交通知
        notificationService.triggerHomeworkSubmissionNotification(studentId, homeworkId);

        return HomeworkSubmissionResult.success(submission);
    }

    public List<HomeworkSubmission> getStudentHomeworkSubmissions(Long studentId, Long courseId) {
        return homeworkRepository.findByStudentIdAndCourseId(studentId, courseId);
    }
}

enum HomeworkSubmissionStatus {
    SUBMITTED,     // 已提交
    LATE,          // 迟交
    GRADED         // 已批改
} 